'''
Created on May 28, 2012

@author: michal
'''


import utils.utils as utils
import logging
import re


class grep (object):
    def __init__(self):
        self.config = utils.readConfig()
        self.logger = logging.getLogger('automatic.regex')
    
    def grepFile(self, inputF, outputF, csvregex, csvdilimiter=','):
        self.logger.debug('Section parameters %s, %s %s' % (inputF, outputF, csvregex)) 
        dictCSV = utils.csvIntoDict(csvregex, delimiter=csvdilimiter)
        self.logger.debug('REGEX dict %s' % dictCSV)
        try:
            inputFile = open(inputF, 'r')
            fileLines=inputFile.readlines()
            inputFile.close()
        except IOError as  e:
            self.logger.error('Couldn\'t open input file %s' % e)
            return
        try:
            outputFile = open(outputF, 'w')
        except IOError as  e:
            self.logger.error('Couldn\'t open input file %s' % e)
            return
        
        for regexline in dictCSV:
            logic=bool(eval(regexline['LOGIC']))
            try:
                flag = getattr(re, regexline['FLAG'])
            except Exception as e:
                self.logger.warning('Incorrect Flag default NO flag used %s' % e)
            finally:
                flag = 0
            pattern = regexline['PATTERN']
            comPat = re.compile(pattern, flag)
            newLines = []
            for line in fileLines:
                if bool(comPat.search(line)) == logic:
                    newLines.append(line)
            fileLines = newLines
        outputFile.writelines(fileLines)
        outputFile.close()
        
                
                
            
        
        
             
        
    
